/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.system.sys.manager;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.common.util.lang.CollectionUtils;
import org.elsfs.cloud.system.api.converter.SysUserConverter;
import org.elsfs.cloud.system.api.dto.co.SysUserEditCO;
import org.elsfs.cloud.system.api.dto.vo.UserInfoVO;
import org.elsfs.cloud.system.api.entity.SysUser;
import org.elsfs.cloud.system.api.entity.SysUserDept;
import org.elsfs.cloud.system.api.entity.SysUserPost;
import org.elsfs.cloud.system.api.entity.SysUserRole;
import org.elsfs.cloud.system.sys.repository.SysUserRepository;
import org.elsfs.cloud.system.sys.repository.mapper.SysUserDeptMapper;
import org.elsfs.cloud.system.sys.repository.mapper.SysUserPostMapper;
import org.elsfs.cloud.system.sys.repository.mapper.SysUserRoleMapper;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户管理
 *
 * @author zeng
 */
@Service
@RequiredArgsConstructor
public class SysUserManager {
  private final SysUserRepository sysUserRepository;
  private final SysUserRoleMapper sysUserRoleMapper;
  private final SysUserDeptMapper sysUserDeptMapper;
  private final PasswordEncoder passwordEncoder;
  private final SysUserConverter sysUserConverter;
  private final SysUserPostMapper sysUserPostMapper;

  /**
   * 创建 用户 1. 创建用户 2. 添加用户和部门关系 3. 添加用户和角色关系
   *
   * @return r
   */
  @DSTransactional
  public Boolean create(SysUserEditCO co) {
    co.setPassword(passwordEncoder.encode("123456"));
    sysUserRepository.save(co);
    var deptId = co.getDeptIds();
    if (CollectionUtils.isNotEmpty(deptId)) {
      List<SysUserDept> depts =
          deptId.stream().map(deptId1 -> new SysUserDept(co.getUserId(), deptId1)).toList();
      sysUserDeptMapper.insertBatch(depts);
    }
    List<String> roleIds = co.getRoleIds();
    if (CollectionUtils.isNotEmpty(roleIds)) {
      List<SysUserRole> userRoles =
          roleIds.stream().map(roleId -> new SysUserRole(co.getUserId(), roleId)).toList();
      sysUserRoleMapper.insertBatch(userRoles);
    }
    List<String> postIds = co.getPostIds();
    if (CollectionUtils.isNotEmpty(postIds)) {
      List<SysUserPost> userPosts =
          postIds.stream().map(postId -> new SysUserPost(co.getUserId(), postId)).toList();
      sysUserPostMapper.insertBatch(userPosts);
    }
    return Boolean.TRUE;
  }

  /**
   * 更新用户 1. 更新用户 2. 删除用户和部门关系 3. 添加用户和部门关系 4. 删除用户和角色关系 5. 添加用户和角色关系
   *
   * @return r
   */
  @DSTransactional
  public Boolean update(SysUserEditCO co) {
    String userId = co.getUserId();
    sysUserRepository.updateById(co);
    sysUserDeptMapper.deleteByUserId(userId);
    sysUserRoleMapper.deleteByUserId(userId);
    sysUserPostMapper.deleteByUserId(userId);
    List<String> deptIds = co.getDeptIds();

    if (CollectionUtils.isNotEmpty(deptIds)) {
      List<SysUserDept> depts =
          deptIds.stream().map(deptId -> new SysUserDept(userId, deptId)).toList();
      sysUserDeptMapper.insertBatch(depts);
    }
    List<String> roleIds = co.getRoleIds();
    if (CollectionUtils.isNotEmpty(roleIds)) {
      List<SysUserRole> roles =
          roleIds.stream().map(roleId -> new SysUserRole(userId, roleId)).toList();
      sysUserRoleMapper.insertBatch(roles);
    }
    List<String> postIds = co.getPostIds();

    if (CollectionUtils.isNotEmpty(postIds)) {
      List<SysUserPost> userPosts =
          postIds.stream().map(postId -> new SysUserPost(userId, postId)).toList();
      sysUserPostMapper.insertBatch(userPosts);
    }
    return Boolean.TRUE;
  }

  /**
   * 删除用户
   *
   * @param userId 用户id
   * @return r
   */
  public Boolean delete(String userId) {
    sysUserRepository.removeById(userId);
    sysUserDeptMapper.deleteByUserId(userId);
    sysUserRoleMapper.deleteByUserId(userId);
    return Boolean.TRUE;
  }

  /**
   * 获取用户信息
   *
   * @param userId 用户id
   * @return 获取用户信息
   */
  public UserInfoVO getUserInfo(String userId) {
    SysUser sysUser = sysUserRepository.getById(userId);
    List<String> deptIds = sysUserDeptMapper.selectByUserId(userId);
    UserInfoVO userInfoVO = sysUserConverter.toUserInfoVO(sysUser);
    userInfoVO.setDeptIds(deptIds);
    return userInfoVO;
  }

  /**
   * 根据角色id获取用户列表
   *
   * @param roleId 角色id
   * @return 用户列表
   */
  public List<SysUser> getUserByRoleId(String roleId) {
    List<String> userIds = sysUserRoleMapper.selectByRoleId(roleId);
    if (CollectionUtils.isEmpty(userIds)) {
      return List.of();
    }
    return sysUserRepository.list(
        Wrappers.lambdaQuery(SysUser.class).in(SysUser::getUserId, userIds));
  }
}
